import uuid

import bluetooth
import time
import sys

# 获取已经链接的蓝牙设备，筛选出手机，然后链接到手机，发送滑动命令
# pip install Pybluez2==0.37
# pip install keyboard

print('Python %s on %s' % (sys.version, sys.platform))

# 获取本机蓝牙地址
def get_locol_address():
    print("本机蓝牙MAC地址:", bluetooth.read_local_bdaddr())

# 查找指定名称的蓝牙设备
def find_buletooth(target_name):
    nearby_devices = bluetooth.discover_devices()
    target_address = None

    for bdaddr in nearby_devices:
        if target_name == bluetooth.lookup_name(bdaddr):
            target_address = bdaddr
        break

    if target_address is not None:
        print("found target bluetooth device with address ", target_address)
        return 1
    else:
        print("could not find target bluetooth device nearby")
        return 0

# 扫描所有附近的蓝牙设备
def san_bluetooth():
    d = []
    nearby_devices = bluetooth.discover_devices(lookup_names=True)
    for addr, name in nearby_devices:

        if "Redmi" in name:
            d.append((addr, name))
        # 假设我们定义的公共浏览组 UUID
        uuidstr = str(uuid.uuid4())  # 生成一个新的 UUID 供示例使用
        print(" %s - %s" % (addr, name))
        # print("  uuid: %s" % uuidstr)
        # services = bluetooth.find_service(name=name, uuid=uuidstr, address=addr)
        # for svc in services:
        #     print("Service Name: %s" % svc["name"])
        #     print(" Host: %s" % svc["host"])
        #     print(" Description: %s" % svc["description"])
        #     print(" Provided By: %s" % svc["provider"])
        #     print(" Protocol: %s" % svc["protocol"])
        #     print(" channel/PSM: %s" % svc["port"])
        #     print(" svc classes: %s " % svc["service-classes"])
        #     print(" profiles: %s " % svc["profiles"])
        #     print(" service id: %s " % svc["service-id"])
        #     print("")
    return d


def find_mobile_devices():
    print("Scanning for Bluetooth devices...")
    nearby_devices = bluetooth.discover_devices(lookup_names=True)

    mobile_devices = []
    for addr, name in nearby_devices:
        # 这里可以根据设备名称筛选
        if "phone" in name.lower() or "mobile" in name.lower():
            print(f"Found mobile device: {name} - {addr}")
            mobile_devices.append((addr, name))

    return mobile_devices

# 连接到蓝牙设备
def connect_to_device(address):
    # 创建蓝牙套接字
    sock = bluetooth.BluetoothSocket(bluetooth.RFCOMM)
    try:
        sock.connect((address, 1))  # 连接到设备
        print(f"Connected to {address}")
        return sock
    except Exception as e:
        print(f"Could not connect to {address}: {e}")
        return None

# 发送滑动命令
def send_slide_command(sock):
    try:
        # 发送自定义滑动命令，这里需要根据手机端设置的接收格式进行调整
        slide_command = "slide_up\n"  # 确保手机端可以正确处理这个命令
        sock.send(slide_command)
        print("Slide command sent.")
    except Exception as e:
        print(f"Failed to send command: {e}")


def main():
    get_locol_address()

    d = san_bluetooth()
    for (address, name) in d:
        print(address, name)
        # 连接到第一个找到的手机
        # address, name = mobile_devices[0]  # 假设连接第一个找到的设备
        # address = "B8:EA:98:93:4C:71"
        # name = "puamac的Redmi K70"
        print(f"Connecting to {name} - {address}...")

        sock = connect_to_device(address)
        print(sock)
        if sock:
            send_slide_command(sock)
            sock.close()  # 关闭连接


if __name__ == "__main__":
    main()